package com.example.lzwphoto.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.lzwphoto.common.R;
import com.example.lzwphoto.dto.CategoryDto;
import com.example.lzwphoto.enity.Category;
import com.example.lzwphoto.service.impl.CategoryServiceImpl;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Desc: 标签分类
 * @Author: LvKun
 * @Date: 2024-02-05
 * @Version: 1.0
 */



@RequestMapping("/category")
@RestController
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryServiceImpl categoryService;

    @GetMapping("/list")
    public R<List> list (Category category) {
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        List<Category> list = categoryService.list();
        ArrayList<CategoryDto> dtos = new ArrayList<>();
        log.info("list: " + list.toString());
//        把一級分类先push到数组里
        list.forEach(item -> {
            if (item.getParentId() == null) {
                CategoryDto categoryDto = new CategoryDto();
                categoryDto.setChildren(new ArrayList<>());
                categoryDto.setId(item.getId());
                categoryDto.setName(item.getName());
                dtos.add(categoryDto);
            }
        });

//        push二级分类
        list.forEach(item -> {
            if (item.getParentId() != null) {
                dtos.forEach(dto -> {
                    if (dto.getId().equals(item.getParentId())) {
                        dto.getChildren().add(item);
                    }
                });
            }
        });

        return  R.success(dtos);
    }

    @PostMapping
    public R<String> save (@RequestBody Category category) {
        categoryService.save(category);
        return  R.success("保存成功");
    }

    @DeleteMapping("{id}")
    public R<String> del (@PathVariable Long id) {
        categoryService.delWithCateGory(id);
        return R.success("删除成功");
    }

    @PutMapping
    public R<String> update (@RequestBody Category category) {
        categoryService.updateById(category);
        return  R.success("修改成功");
    }

}
